package com.learn.image.utils;



import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.swing.JLabel;

import static com.learn.image.constant.Constant.*;


/**
 * 图片水印工具类
 *
 * @author: Administrator
 * @createTime: 2023/11/28 0028 17:35
 * @version: 1.0
 */
public class WaterMarkUtil {



    /**
     * 水印横向位置
     */
    private static final int POSITION_WIDTH = 50;
    /**
     * 水印纵向位置
     */
    private static final int POSITION_HEIGHT = 100;


    /**
     * 添加水印方法
     */
    public static void imageMarkWater(String text, InputStream inputStream, OutputStream outputStream, Integer degree, String typeName) {
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(inputStream);
            int imgWidth = srcImg.getWidth(null);
            int imgHeight = srcImg.getHeight(null);
            BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线端的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印的旋转角度
            if (isNotNull(degree)) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            // 5、设置水印文字颜色
            g.setColor(WATER_COLOR);
            // 6、设置水印文字字体
            g.setFont(FONT);
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));
            // 8、第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
            g.drawString(text, POSITION_WIDTH, POSITION_HEIGHT);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            ImageIO.write(buffImg, typeName.toLowerCase(), outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean isNotNull(Integer degree) {
        return null != degree;
    }

    /**
     * @param waterMarkContent 水印内容
     * @param inputStream      inputStream
     * @param outImgStream     outImgStream
     * @param degree           设置水印文字的旋转角度
     * @param extension        图片格式
     * @return void
     */
    public static void addWatermark(String waterMarkContent,
                                    InputStream inputStream, OutputStream outImgStream,Integer degree, String extension) {

        try {
            Image srcImg = ImageIO.read(inputStream); //得到文件转化为图片

            int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
            int srcImgHeight = srcImg.getHeight(null);//获取图片的高
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();//得到画笔
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setColor(Color.white);        //设置水印颜色
            g.setFont(FONT);                //设置字体
            //设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            if (isNotNull(degree)) {

                g.rotate(Math.toRadians(degree), bufImg.getWidth(), bufImg.getHeight());//设置水印旋转
            }
            JLabel label = new JLabel(waterMarkContent);
            FontMetrics metrics = label.getFontMetrics(FONT);
            int width = metrics.stringWidth(label.getText());//文字水印的宽
            int rowsNumber = srcImgHeight / width;// 图片的高  除以  文字水印的宽    ——> 打印的行数(以文字水印的宽为间隔)
            int columnsNumber = srcImgWidth / width;//图片的宽 除以 文字水印的宽   ——> 每行打印的列数(以文字水印的宽为间隔)
            //防止图片太小而文字水印太长，所以至少打印一次
            if (rowsNumber < 1) {
                rowsNumber = 1;
            }
            if (columnsNumber < 1) {
                columnsNumber = 1;
            }
            for (int j = 0; j < rowsNumber; j++) {
                for (int i = 0; i < columnsNumber; i++) {
                    g.drawString(waterMarkContent, i * width + j * width, -i * width + j * width);//画出水印,并设置水印位置
                }
            }
            g.dispose();// 释放资源
            // 生成图片
            ImageIO.write(bufImg, extension, outImgStream);
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        } finally {
            try {
                if (outImgStream != null) {
                    outImgStream.flush();
                    outImgStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                e.getMessage();
            }
        }
    }


    /**
     * imgFile 图像文件
     * imageFileName 图像文件名
     * uploadPath 服务器上上传文件的相对路径
     * realUploadPath 服务器上上传文件的物理路径
     */
    public String watermarkAdd(File imgFile, String imageFileName, String uploadPath, String realUploadPath ) {

        String imgWithWatermarkFileName = "watermark_" + imageFileName;
        OutputStream os = null;

        try {
            // 源图片
            Image image = ImageIO.read(imgFile);

            int width = image.getWidth(null);
            int height = image.getHeight(null);

            BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);  // ①
            // 得到画笔对象
            Graphics2D g = bufferedImage.createGraphics();  // ②
            g.drawImage(image, 0, 0, width,height,null);  // ③

            String logoPath = realUploadPath + "/" +"/img-folder/20231129101118.png" ;  // 水印图片地址
            File logo = new File(logoPath);        // 读取水印图片
            Image imageLogo = ImageIO.read(logo);

            int markWidth = imageLogo.getWidth(null);    // 水印图片的宽度和高度
            int markHeight = imageLogo.getHeight(null);

            g.setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA) );  // 设置水印透明度
            g.rotate(Math.toRadians(-10), (double) bufferedImage.getWidth() /2, (double) bufferedImage.getHeight() /2);  // 设置水印图片的旋转度


            //添加单个水印
            double x2 = width * 0.9 - markWidth;
            double y2 = height * 0.9 - markHeight;
            g.drawImage(imageLogo, new Double(x2).intValue(), new Double(y2).intValue(), null);  // ④

          /*  // 循环添加多个水印logo
          double count = 1.5;
            while ( x < width*count ) {  // 循环添加多个水印logo
                y = -height / 2;
                while( y < height*count ) {
                    g.drawImage(imageLogo, x, y, null);  // ④
                    y += markHeight + yInterval;
                }
                x += markWidth + xInterval;
            }*/

            g.dispose();

            os = Files.newOutputStream(Paths.get(realUploadPath + "/" + imgWithWatermarkFileName));
//            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os); // ⑤
//            en.encode(bufferedImage); // ⑥

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return uploadPath + "/" + imgWithWatermarkFileName;
    }
}
